// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: linchuan

#include "coin2/exchange/ftx_common/api_order/native_private_client.h"

#include <list>
#include <memory>
#include <string>

#include "coin2/exchange/base/api_util/url_params_builder.h"
#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/ftx/symbology/product.h"
#include "coin2/exchange/ftx_futures/symbology/product.h"

using AsioHttpContextList = std::list<std::shared_ptr<AsioHttpContext>>;

auto FtxNativePrivateClient::GetRestOrderParams(const OrderSpec& order_spec, int64_t proc_order_id)
    -> RestParams {
  auto params = RestParams();

  params.set_market(order_spec.product);
  if (symcache_->is_spot()) {
    using coin2::exchange::ftx::symbology::FtxProduct;
    auto product = FtxProduct::FromStr(order_spec.product, order_spec.order_created_time);
    auto product_holder = GetProductHolder(product, order_spec.order_created_time);
    auto formatter = product_holder->product_info().order_formatter();
    params.set_price(formatter.FormatPrice(order_spec.price));
    params.set_size(formatter.FormatQty(order_spec.qty));
  } else if (symcache_->is_futures()) {
    using coin2::exchange::ftx_futures::symbology::FtxFuturesProduct;
    auto product = FtxFuturesProduct::FromStr(order_spec.product, order_spec.order_created_time);
    auto product_holder = GetProductHolder(product, order_spec.order_created_time);
    auto formatter = product_holder->product_info().order_formatter();
    params.set_price(formatter.FormatPrice(order_spec.price));
    params.set_size(formatter.FormatQty(order_spec.qty));
  } else {
    NOTREACHED() << "unknown MarketType" << mea_.SnakeString();
  }
  params.set_client_id(std::to_string(proc_order_id));

  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_side("buy");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_side("sell");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }

  if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_type("market");
  } else {
    params.set_type("limit");
  }
  if (order_spec.post_only) {
    params.set_post_only("True");
  }
  if (order_spec.duration == coin::proto::OrderDuration::IOC_ORDER) {
    params.set_ioc("True");
  }

  return params;
}

auto FtxNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context) -> RestParams {
  auto params = RestParams();
  if (order_context.has_exchange_order_id()) {
    params.set_order_id(order_context.exchange_order_id());
  } else {
    params.set_client_id(std::to_string(order_context.proc_order_id()));
  }
  return params;
}

FtxNativePrivateClient::FtxNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config_override) {
  mea_ = mea;
  NativeClientConfig config;
  config.set_rest_host("ftx.com");
  config.set_rest_host_port(443);
  config.MergeFrom(config_override);
  LOG(INFO) << "[FtxNativePrivateClient] config: " << config.DebugString();
  // for order submit/cancel
  order_auths_.Construct<FtxRestAuth, NativeClientConfig>(config);
  // for rest query
  // for now, for ftx, the domain only for normal and whitelisted IP, so just hard code it first
  config.set_rest_host("ftx.com");
  config.set_rest_host_port(443);
  auths_.Construct<FtxRestAuth, NativeClientConfig>(config);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryBalance() {
  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/wallet/balances", &builder);
  context->query_type = OrderSubTopicId::REST_ACCOUNT_BALANCE;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryPosition() {
  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/positions", &builder);
  context->query_type = OrderSubTopicId::REST_ACCOUNT_POSITION;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryAccount() {
  CHECK(false);
  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/account", &builder);
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryOpenOrders(const RestParams& params) {
  UrlParamsBuilder builder;
  builder.PutGet("market", params.market());
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/orders", &builder);
  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryOrders(const RestParams& params) {
  UrlParamsBuilder builder;
  builder.PutGet("market", params.market());
  builder.PutGet("limit", params.limit());
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/orders/history", &builder);
  context->query_type = OrderSubTopicId::REST_ALL_ORDERS;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryTrades(const RestParams& params) {
  UrlParamsBuilder builder;
  builder.PutGet("market", params.market());
  builder.PutGet("limit", params.limit());
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/fills", &builder);
  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  return std::shared_ptr<AsioHttpContext>(context);
}


std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryDeposits(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    LOG(ERROR) << "Rate limit! QueryDeposits not submit!";
    return {};
  }

  UrlParamsBuilder builder;
  if (params.has_start_time() && params.has_end_time()){
    builder.PutGet("start_time", params.start_time());
    builder.PutGet("end_time", params.end_time());
  }
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/wallet/deposits", &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = FtxOrderSubTopicId::REST_DEPOSIT;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::QueryWithdraws(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    LOG(ERROR) << "Rate limit! QueryWithdraws not submit!";
    return {};
  }

  UrlParamsBuilder builder;
  if (params.has_start_time() && params.has_end_time()){
    builder.PutGet("start_time", params.start_time());
    builder.PutGet("end_time", params.end_time());
  }
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/api/wallet/withdrawals", &builder);
  Push(1, ts, ActionType::QUERY);

  context->query_type = FtxOrderSubTopicId::REST_WITHDRAWAL;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::PlaceOrder(const RestParams& params) {
  UrlParamsBuilder builder;
  builder.PutPost("market", params.market());
  builder.PutPost("side", params.side());
  builder.PutPost("type", params.type());
  builder.PutPost("ioc", params.ioc());
  builder.PutPost("price", params.price());
  builder.PutPost("size", params.size());
  builder.PutPost("clientId", params.client_id());
  builder.PutPost("postOnly", params.post_only());
  builder.PutPost("reduceOnly", params.reduce_only());
  auto* context =
      order_auths_.GetRandom()->CreateRequestByPostWithSignature("/api/orders", &builder);

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::CancelOrder(const RestParams& params) {
  UrlParamsBuilder builder;
  CHECK(params.has_order_id() != params.has_client_id())
      << "only one of order_id and client_id can be set!" << params.DebugString();

  if (params.has_order_id() > 0) {
    auto* context = order_auths_.GetRandom()->CreateRequestByDeleteWithSignature(
        "/api/orders/" + params.order_id(),
        &builder);

    context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
    return std::shared_ptr<AsioHttpContext>(context);
  } else {
    auto* context = order_auths_.GetRandom()->CreateRequestByDeleteWithSignature(
        "/api/orders/by_client_id/" + params.client_id(),
        &builder);

    context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
    return std::shared_ptr<AsioHttpContext>(context);
  }
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::CancelAllOrder(const RestParams& params) {
  UrlParamsBuilder builder;
  builder.PutPost("market", params.market());
  auto* context =
      order_auths_.GetRandom()->CreateRequestByDeleteWithSignature("/api/orders", &builder);
  context->query_type = OrderSubTopicId::MULTI_CANCEL_RESPONSE;
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::PlaceOrderNorm(
    const OrderExecution& order_exe) {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::CancelOrderNorm(
    const OrderExecution& order_exe) {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::SubmitOrderExecution(
    const OrderExecutionProto& order) {
  switch (order.type()) {
    case OrderExecutionProto::SUBMIT_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return PlaceOrder(params);
    }
    case OrderExecutionProto::CANCEL_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params = GetRestOrderParams(*order_spec, order.proc_order_id());
      return CancelOrder(params);
    }
    default: {
      return nullptr;
    }
  }
}

std::shared_ptr<AsioHttpContext> FtxNativePrivateClient::SubmitRestQuery(
    const RestQueryProto& query) {
  RestParams params;
  switch (query.type()) {
    case RestQueryProto::QUERY_ACCOUNT_BALANCE: {
      return QueryBalance();
    }
    case RestQueryProto::QUERY_ACCOUNT_POSITION: {
      return QueryPosition();
    }
    case RestQueryProto::QUERY_OPEN_ORDERS: {
      return QueryOpenOrders(params);
    }
    default: {
      return nullptr;
    }
  }
}

AsioHttpContextList FtxNativePrivateClient::SubmitRestQueryList(const RestQueryProto& query) {
  AsioHttpContextList list;
  switch (query.type()) {
    case RestQueryProto::QUERY_TRANSFERS: {
      RestParams params;
      params.set_start_time(query.start_time() / 1000'000'000);
      params.set_end_time(query.end_time() / 1000'000'000);
      list.emplace_back(QueryDeposits(params));
      list.emplace_back(QueryWithdraws(params));
      break;
    }
    default: {
      return list;
    }
  }

  return list;
}